<?php

namespace common\repositories\picture;

use Yii;
use common\repositories\BaseRepository;
use common\entities\picture\PictureEntity;

class PictureRepository extends BaseRepository {
    /**
     * 添加或修改图片信息
     * @param $data array 图片信息
     * @return bool
     */
    public function save($data)
    {
        if(empty($data["id"])){
            $picEntity = new PictureEntity();
            $picEntity->created_time = date("Y-m-d :H:i:s",time());
        }else{
            $picEntity = PictureEntity::find()->where(['id'=>$data["id"]])->one();
            if (empty($picEntity)){
                return false;
            }
        }
        $picEntity->title = $data["title"];
        $picEntity->is_able = $data["is_able"];
        $picEntity->type = $data["type"];
        $picEntity->redirect_url = isset($data["redirect_url"]) ? $data["redirect_url"] : "";
        $picEntity->sort = $data["sort"];
        $picEntity->picture = $data["picture"];
        $picEntity->modified_time = date("Y-m-d :H:i:s",time());
        $picEntity->bg_color = $data["bg_color"];
        return $picEntity->save();
    }

    /**
     * 根据id取图片信息
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getPicInfoById($id)
    {
        return $picInfo = PictureEntity::find()
            ->select(["id", "type", "title", "is_able", "redirect_url", "picture", "sort"])
            ->where(["id" => $id])
            ->asArray()
            ->one();
    }

    /**
     * 根据id删除图片
     */
    public function deleteById($id)
    {
        return PictureEntity::find()->where(["id"=>$id])->one()->delete();
    }

    /**
     * 更新启用状态
     * @param $id int id
     * @param $status int is_able
     * @return bool
     */
    public function updateAble($id, $status)
    {
        $picEntity = PictureEntity::find()->where(["id"=>$id])->one();
        if (empty($picEntity)){
            return false;
        }
        $picEntity->is_able = $status;
        return $picEntity->save();
    }

    /**
     * 后台管理图片列表
     * @param $keyword string 关键字
     * @param $page int 页码
     * @param $perPage int 每页条数
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getPicList($keyword, $page,$perPage)
    {
        $offset = $page * $perPage;
        $where = [];
        if (!empty($keyword)){
            $where = ["like","title", $keyword];
        }
        $picList = PictureEntity::find()
            ->select(["id", "type", "title", "is_able", "redirect_url", "modified_time", "sort","picture", 'bg_color'])
            ->where($where)
            ->offset($offset)
            ->limit($perPage)
            ->orderBy("type asc ,created_time desc")
            ->asArray()
            ->all();
        $total = PictureEntity::find()
            ->select("count(*)")
            ->where($where)
            ->orderBy("type asc ,created_time desc")
            ->scalar();
        return [$picList,$total];
    }
}